package com.imoblife.brainwavestus.database;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;

import com.imoblife.brainwavestus.oldDownloadFrame.DownLoadItemPragrame;
import com.imoblife.brainwavestus.util.ProductUtil;

import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Xml;

public class SQLiteManager extends SQLiteOpenHelper {

	private static final String TAG = "SQLiteManager";
	private static Context singContext;
	private static final int sqliteVersionCode = 6; 

	public static class DownTaskTable {
		public static final String TB_NAME = "DownLoadTaskTable";// ��������ı���
		public static final String ID = "_id";
		public static final String NAME = "name";
		public static final String SIZE = "size";
		public static final String VERSION = "version";
		public static final String STATE = "state";
		public static final String PARENT = "parent";
		public static final String LEVEL = "level";
		public static final String CATEGORY = "category";
		public static final String CHENGETIME = "chengetime";
		public static final String STATE_EXTR = "state_extr";
		public static final String TITLE = "title";
	}

	// ��Ʒ��
	public static class ShopTable {
		public static final String TB_NAME = "ShopTable";//
		public static final String ID = "_id";
		public static final String NAME = "name";
		public static final String CATEGORY = "category";
		public static final String TITLE = "title";
	}

	// ��tapjoy id ��j�� id;
	public static class TJTable {
		public static final String TB_NAME = "TBTable";
		public static final String NAME = "name";
		public static final String TBID = "tj_id";
	}

	private static SQLiteManager liteManager;
	private static SQLiteDatabase database;

	private SQLiteManager(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);

	}

	public void updateData(Context context) {

		if (laugIsChenge(context)) {

			HashMap<String, Integer> hashMap = new HashMap<String, Integer>();

			Cursor cursor = getDatabaseInstence(context).query(
					DownTaskTable.TB_NAME,
					new String[] { DownTaskTable.NAME, DownTaskTable.STATE },
					DownTaskTable.STATE + "!=?",
					new String[] { DownLoadItemPragrame.DOWN_STATE_NOT_ENBLE
							+ "" }, null, null, null);

			while (cursor.moveToNext()) {
				hashMap.put(cursor.getString(0), cursor.getInt(1));
			}

			cursor.close();

			context.getDatabasePath("SQLiteManager.db").delete();
			singContext = context;
			liteManager = new SQLiteManager(context, "SQLiteManager.db", null,
					sqliteVersionCode);
			database = liteManager.getWritableDatabase();

			Iterator<Entry<String, Integer>> iterable = hashMap.entrySet()
					.iterator();

			while (iterable.hasNext()) {
				Entry<String, Integer> entry = iterable.next();
				ContentValues values = new ContentValues();
				values.put(DownTaskTable.STATE, entry.getValue());
				getDatabaseInstence(context).update(DownTaskTable.TB_NAME, values,
						DownTaskTable.NAME + "=?",
						new String[] { entry.getKey() });
			}
			hashMap.clear();
		}

	}

	private void confirmLang(Context context) {
		SharedPreferences sharedPreferences = context.getSharedPreferences(
				"Lang", 0);
		sharedPreferences.edit().putString("Lang", ProductUtil.getLang()).commit();
	}

	public static synchronized SycSqlite getDatabaseInstence(Context context) {
		singContext = context;
		if (liteManager == null) {
			liteManager = new SQLiteManager(context, "SQLiteManager.db", null,
					sqliteVersionCode);

		}

		if (database == null || !database.isOpen()) {
			database = liteManager.getWritableDatabase();
		}

		return new SycSqlite(database);
	}

	public static synchronized SQLiteManager getInstence(Context context) {

		singContext = context;
		if (liteManager == null) {
			liteManager = new SQLiteManager(context, "SQLiteManager.db", null,
					sqliteVersionCode);

		}
		return liteManager;
	}

	protected boolean laugIsChenge(Context context) {
		SharedPreferences sharedPreferences = context.getSharedPreferences(
				"Lang", 0);
		return !sharedPreferences.getString("Lang", "").equals(ProductUtil.getLang());

	}

	public void onCreate(SQLiteDatabase db) {
		creatDownloadTable(db);
		creatShopTable(db);
		createTJTable(db);

		try {
			initializeTJTable(db);
			initializeDownloadTasks(db);
			confirmLang(singContext);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void creatShopTable(SQLiteDatabase db) {
		db.execSQL("CREATE TABLE IF NOT EXISTS " + ShopTable.TB_NAME + " ("
				+ ShopTable.ID + " INTEGER," + ShopTable.NAME
				+ " text PRIMARY KEY," + ShopTable.CATEGORY + " text,"
				+ ShopTable.TITLE + " text)");
	}

	private void creatDownloadTable(SQLiteDatabase db) {
		db.execSQL("CREATE TABLE IF NOT EXISTS " + DownTaskTable.TB_NAME + " ("
				+ DownTaskTable.ID + " INTEGER," + DownTaskTable.NAME
				+ " text PRIMARY KEY," + DownTaskTable.PARENT + " text,"
				+ DownTaskTable.CATEGORY + " text," + DownTaskTable.CHENGETIME
				+ " text," + DownTaskTable.SIZE + " INTEGER,"
				+ DownTaskTable.STATE + " INTEGER," + DownTaskTable.LEVEL
				+ " INTEGER," + DownTaskTable.VERSION + " INTEGER,"
				+ DownTaskTable.STATE_EXTR + " INTEGER," + DownTaskTable.TITLE
				+ " text)");
	}

	private void createTJTable(SQLiteDatabase db) {

		db.execSQL("CREATE TABLE IF NOT EXISTS " + TJTable.TB_NAME + " ("
				+ TJTable.NAME + " text PRIMARY KEY," + TJTable.TBID + " text)");
	}

	private void initializeTJTable(SQLiteDatabase db) throws IOException,
			JSONException {

		InputStream inputStream = null;
		inputStream = singContext.getAssets().open("tb_id.json");
		byte[] data = new byte[inputStream.available()];
		inputStream.read(data);
		String string = new String(data);
		inputStream.close();

		JSONObject jsonObject = new JSONObject(string);
		JSONArray jsonArray = jsonObject.getJSONArray("ItemsArray");

		final int size = jsonArray.length();

		for (int i = 0; i < size; i++) {

			String name = jsonArray.getJSONObject(i).getString("name");
			String tj_id = jsonArray.getJSONObject(i).getString("tj_id");
			ContentValues contentValues = new ContentValues();
			contentValues.put(TJTable.NAME, name);
			contentValues.put(TJTable.TBID, tj_id);

			long l = System.currentTimeMillis();
			db.replace(TJTable.TB_NAME, null, contentValues);
		}

	}

	/**
	 * ���Ĭ�ϵ���Ŀ����ݿ�
	 * 
	 * @param db
	 */
	private void initializeDownloadTasks(SQLiteDatabase db) {
		long l = System.currentTimeMillis();
		try {

			InputStream inputStream = singContext.getResources().getAssets()
					.open("des/" + ProductUtil.getLang() + "/products_table.xml");

			XmlPullParser parser = Xml.newPullParser();

			parser.setInput(inputStream, "utf-8");

			int evenType = parser.getEventType();

			String category = null;

			while (evenType != XmlPullParser.END_DOCUMENT) {

				if (XmlPullParser.START_TAG == evenType) {

					if ("Product".equals(parser.getName())) {

						ContentValues contentValues = new ContentValues();

						for (int i = 0; i < parser.getAttributeCount(); i++) {

							String context = parser.getAttributeName(i);

							if (context.equals("category")) {
								category = parser.getAttributeValue(i);
								contentValues.put(
										SQLiteManager.ShopTable.CATEGORY,
										parser.getAttributeValue(i));

							} else if (context.equals("name")) {

								contentValues.put(SQLiteManager.ShopTable.NAME,
										parser.getAttributeValue(i));
							} else if (context.equals("title")) {

								contentValues.put(
										SQLiteManager.ShopTable.TITLE,
										parser.getAttributeValue(i));
							}
						}

						db.insert(ShopTable.TB_NAME, null, contentValues);
					} else if ("DownLoadItem".equals(parser.getName())) {

						ContentValues values = new ContentValues();
						for (int i = 0; i < parser.getAttributeCount(); i++) {
							values.put(parser.getAttributeName(i),
									parser.getAttributeValue(i));
						}
						values.put(SQLiteManager.DownTaskTable.CATEGORY,
								category);
						db.insert(SQLiteManager.DownTaskTable.TB_NAME, null,
								values);
					}
				}
				evenType = parser.next();
			}
			inputStream.close();

		} catch (Exception e) {

			e.printStackTrace();
		}
		//ToolsUtil.debug(TAG, "���� ������ݿ�" + (System.currentTimeMillis() - l));
	}

	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

		if (newVersion == 6) {
			db.execSQL("DROP TABLE IF EXISTS " + DownTaskTable.TB_NAME);
			db.execSQL("DROP TABLE IF EXISTS " + ShopTable.TB_NAME);
			db.execSQL("DROP TABLE IF EXISTS " + TJTable.TB_NAME);
			onCreate(db);
		}
	}

	public void closeDataBase() {

	}

}
